#!/bin/sh

# configure/install nvm
source_nvm() {
  if [ -f ~/.nvm/nvm.sh ]; then
    echo 'Sourcing nvm from ~/.nvm'
    . ~/.nvm/nvm.sh
  elif command -v brew; then
    _brew_prefix=$(brew --prefix nvm)
    if [ -f "$_brew_prefix/nvm.sh" ]; then
      echo "Sourcing nvm from brew ($_brew_prefix)"
      . "$_brew_prefix"/nvm.sh
    fi
  else
    echo "Please make sure nvm is installed (correctly), please follow the installation instructions
              at: https://github.com/nvm-sh/nvm  
            "
  fi
}

source_nvm
# automatically change node version to the one indicated in .nvmrc
nvm use

# Prevent errors on shallow clones
if git rev-parse --verify HEAD@{1} >/dev/null 2>&1; then
  # Check if package-lock.json changed
  if git diff --name-only HEAD@{1} HEAD 2>/dev/null | grep -q "^package-lock.json$"; then
    echo "📦 package-lock.json changed, running npm install..."
    npm install --prefer-offline --no-audit
  fi

  # Check if values-schema.yaml changed
  if git diff --name-only HEAD@{1} HEAD 2>/dev/null | grep -q "^values-schema.yaml$"; then
    echo "🔨 values-schema.yaml changed, regenerating schema..."
    npm run gen:chart-schema
  fi
else
  echo "Skipping file change detection: Not enough Git history"
fi
